<template>
  <BasicDrawer v-bind="$attrs" @register="registerModal" destroyOnClose :title="title" :width="'80%'" @ok="handleSubmit">
    <BasicForm @register="registerForm" name="UfMallOrderDetailForm" />
    <BasicForm @register="registerRefundForm" name="UfMallOrderRefundForm" />
    <BasicTable @register="registerTable" :rowSelection="rowSelection" />
  </BasicDrawer>
</template>

<script lang="ts" setup>
  import { ref, computed, unref } from 'vue';
  import { BasicModal, useModalInner } from '/@/components/Modal';
  import { BasicDrawer, useDrawerInner } from '/@/components/Drawer';
  import { BasicForm, FormSchema, useForm } from '/@/components/Form/index';
  import { formSchema } from '../UfMallOrder.data';
  import { refundOrder, saveOrUpdate, shipOrder } from "../UfMallOrder.api";
  import { BasicTable } from '@/components/Table';
  import { columns } from '@/views/order/UfMallOrderItem.data';
  import { list } from '@/views/order/UfMallOrderItem.api';
  import { useListPage } from '@/hooks/system/useListPage';
  import { useMessage } from '@/hooks/web/useMessage';
  // Emits声明
  const emit = defineEmits(['register', 'success']);
  const isUpdate = ref(true);
  const isDetail = ref(false);
  const value = ref({});
  const record = ref({});
  let refundFormSchema: FormSchema[] = [];
  refundFormSchema.push({
    label: '退款金额',
    field: 'refundAmount',
    component: 'Input',
    colProps: { span: 12 },
  });
  refundFormSchema.push({
    label: '类型',
    field: 'refundType',
    component: 'RadioButtonGroup',
    colProps: { span: 12 },
    componentProps: ({ formModel }) => {
      return {
        disabled: true,
        options: [
          {
            label: '仅退款',
            value: 'ONLY_RETURN_MONEY',
          },
          {
            label: '退货退款',
            value: 'RETURN_MONEY_AND_PRODUCT',
          },
        ],
      };
    },
  });
  refundFormSchema.push({
    label: '物流单号',
    field: 'refundFlowId',
    component: 'Input',
    componentProps: ({ formModel }) => {
      return {
        disabled: true,
      };
    },
  });
  refundFormSchema.push({
    label: '退款原因',
    field: 'refundReason',
    component: 'Input',
    componentProps: ({ formModel }) => {
      return {
        disabled: true,
      };
    },
  });
  refundFormSchema.push({
    label: '',
    field: 'id',
    component: 'Input',
    show: false,
  });
  //表单配置
  const [registerForm, { setProps, resetFields, setFieldsValue, scrollToField }] = useForm({
    labelWidth: 150,
    schemas: formSchema,
    showActionButtonGroup: false,
    baseColProps: { span: 24 },
  });

  const [registerRefundForm, { validate: validateRefundForm, setFieldsValue: setRefundFieldsValue }] = useForm({
    labelWidth: 150,
    schemas: refundFormSchema,
    showActionButtonGroup: false,
    baseColProps: { span: 24 },
  });
  //表单赋值
  const [registerModal, { setDrawerProps, closeDrawer }] = useDrawerInner(async (data) => {
    //重置表单
    await resetFields();
    setDrawerProps({
      confirmLoading: false,
      showCancelBtn: !!data?.showFooter,
      showOkBtn: !!data?.showFooter,
      showFooter: !!data?.showFooter,
    });
    isUpdate.value = !!data?.isUpdate;
    isDetail.value = !!data?.showFooter;
    if (unref(isUpdate)) {
      record.value = data.record;
      //表单赋值
      await setFieldsValue({
        ...data.record,
      });
      if (!!data?.showFooter) {
        data.record.refundAmount = data.record.actualTotal;
      }
      await setRefundFieldsValue({
        ...data.record,
      });
      value.value = data.record;
    }
    // 隐藏底部时禁用整个表单
    setProps({ disabled: !data?.showFooter });
  });
  //设置标题
  const title = '退货/退款';

  const { createMessage, createConfirm } = useMessage();

  //表单提交事件
  async function handleSubmit(v) {
    try {
      let values = await validateRefundForm();
      if (values.refundAmount > record.value.actualTotal) {
        createMessage.error('退款金额不能超过订单总额');
        return;
      }
      setDrawerProps({ confirmLoading: true });
      createConfirm({
        iconType: 'warning',
        title: '退款操作',
        content: '确定要进行退款，本次退款金额（' + values.refundAmount + '）？\r\n如是退货退款，请确认已收到退回商品！',
        okText: '确认并退款',
        onOk: async function () {
          //提交表单
          await refundOrder(values);
          //关闭弹窗
          closeDrawer();
          //刷新列表
          emit('success');
        },
      });
    } catch ({ errorFields }) {
      if (errorFields) {
        const firstField = errorFields[0];
        if (firstField) {
          scrollToField(firstField.name, { behavior: 'smooth', block: 'center' });
        }
      }
      return Promise.reject(errorFields);
    } finally {
      setDrawerProps({ confirmLoading: false });
    }
  }

  //注册table数据
  const { prefixCls, tableContext, onExportXls, onImportXls } = useListPage({
    pagination: false,
    tableProps: {
      title: '',
      api: list,
      columns,
      canResize: false,
      showTableSetting: false,
      pagination: false,
      formConfig: {
        //labelWidth: 120,
        autoSubmitOnEnter: true,
        showAdvancedButton: true,
        fieldMapToNumber: [],
        fieldMapToTime: [],
      },
      actionColumn: {
        width: 200,
        fixed: 'right',
        ifShow: false,
      },
      beforeFetch: (params) => {
        return Object.assign(params, { orderNumber: value.value.orderNumber });
      },
    },
  });

  const [registerTable, { reload }, { rowSelection, selectedRowKeys }] = tableContext;
</script>

<style lang="less" scoped>
  /** 时间和数字输入框样式 */
  :deep(.ant-input-number) {
    width: 100%;
  }

  :deep(.ant-calendar-picker) {
    width: 100%;
  }
</style>
